<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\media_account;


use app\common\model\media\Media;
use app\common\model\media_account\MediaAccount;
use app\common\model\media_account\MediaAccountAssociation;
use app\common\model\media_account\MediaAuth;
use app\common\service\media\BdService;
use app\common\service\media\KsService;
use app\common\service\media\OceanengineService;
use app\common\logic\BaseLogic;
use app\common\service\media\UcService;
use app\common\service\media\VivoService;
use think\facade\Log;


/**
 * MediaAccount逻辑
 * Class MediaAccountLogic
 * @package app\adminapi\logic
 */
class MediaAccountLogic extends BaseLogic
{


    /**
     * 获取授权地址
     *
     * @param array $params
     * @return boolean | string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getEmpowerUrl(array $params)
    {
        $authId = $params['auth_id'] ?? 0;

        $mediaId = MediaAuth::where('id', $authId)->value('media_id');

        switch ($mediaId) {
            case Media::SOURCE_JL :
                return (new OceanengineService($authId))->getEmpowerUrl($authId);
            case Media::SOURCE_UC : // UC不需要授权，单独处理原页面加载账户
                (new UcService($authId))->getAdAccount($authId);
                return config('media.redirect_url') . '&media=' . Media::SOURCE_UC;
            case Media::SOURCE_KS :
                return (new KsService($authId))->getEmpowerUrl($authId);
            case Media::SOURCE_BD :
                return (new BdService($authId))->getEmpowerUrl($authId);
            case Media::SOURCE_OPPO :
                return (new VivoService($authId))->getEmpowerUrl($authId);
            case Media::SOURCE_VIVO :
                return (new VivoService($authId))->getEmpowerUrl($authId);
            default :
                return false;
        }
    }


    /**
     * 媒体授权回调
     *
     * @param $authCode
     * @param $state
     * @param $media
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function empower($authCode, $authId, $media, $usrId = 0): bool
    {
        switch ($media) {
            case Media::SOURCE_JL :
                $oceanengineService = new OceanengineService($authId);
                $tokenArr           = $oceanengineService->getAccessToken($authCode);
                $oceanengineService->saveAdvertiser($authId, $tokenArr);
                break;
            case Media::SOURCE_KS :
                $ksService = new KsService($authId);
                list($advertiserId, $token) = $ksService->getToken($authCode);
                $ksService->getAdvertiser($authId, $advertiserId, $token);
                break;
            case Media::SOURCE_BD :
                $bdService = new BdService($authId);
                list($advertiserId, $token, $openId) = $bdService->getToken($authCode, $usrId);
                $userData = $bdService->getUserInfo($openId, $token, $advertiserId);
                $userName = $userData['masterName'] ?? '';
                $bdService->getAdvertiser($authId, $advertiserId, $token, $userName);
                break;
            case Media::SOURCE_VIVO :
                $vivoService = new VivoService($authId);
                $accessToken = $vivoService->getToken($authCode);
                $vivoService->getAdvertiser($authId, $accessToken);
                break;
            default :
                return false;
        }

        return true;
    }


    /**
     * 生成推广链接时候使用
     *
     * @param $admin_id
     * @return array
     */
    public static function getALlByAdminId($admin_id): array
    {
        return MediaAccountAssociation::alias('maa')->leftjoin('media_account ma', 'maa.media_account_id = ma.id')->where('ma.status', 1)->where('maa.admin_id', $admin_id)->field('ma.id,ma.advertiser_name')->order('id desc')->select()->toArray();
    }


    /**
     * 绑定推广ID
     *
     * @param $accountId
     * @param $promotionLinkId
     * @return bool
     */
    public static function bindPromotion($accountId, $promotionLinkId)
    {
        if (!$accountId || !$promotionLinkId) {

            return false;
        }

        $account = MediaAccount::where('id', $accountId)->findOrEmpty();
        if ($account->isEmpty()) {

            return false;
        }
        $account->promotion_link_id = $promotionLinkId;

        return $account->save();
    }


    /**
     * 绑定事件源ID
     *
     * @param $accountId
     * @param $promotionLinkId
     * @return bool
     */
    public static function bindSrc($accountId, $srcId)
    {
        if (!$accountId || !$srcId) {

            return false;
        }

        $account = MediaAccount::where('id', $accountId)->findOrEmpty();
        if ($account->isEmpty()) {

            return false;
        }
        $account->src_id = $srcId;

        return $account->save();
    }


    /**
     * 设置项目组
     *
     * @param $teamId
     * @param array $accountIds
     * @return bool
     */
    public static function setTeam($teamId, $accountIds = [])
    {
        if (!$teamId || !$accountIds) {

            return false;
        }

        MediaAccount::whereIn('id', $accountIds)->update(['team_id' => $teamId, 'update_time' => time()]);

        return true;
    }
}
